<?php
class NoticesController extends AppController{
    
    var $name = 'Notices';
    var $uses = array("Attachment","Notice","User",
    "Economics_state","User_msg_relationship","Msg","Attachment","User",
     					"CompInstitution","CompAchievement","Company","Project","Codetype","ProCvalue",
     					"Group","Followinfo","Constant","CompPerson","Codevalue",
                       "CompanyPatent","CompPage","DevelopmentCost","CompPerson","Achievement",
                       "CompEconomic","CompFinanc","CompTalent","CompTrackinfo","CompType",
                       "CompTechnology","Informationfrom",
                       "CompCarrierlease","CompDormitorylease","CompLearentbonus","CompResearchrentbonus",
                       "CompJobapply","CompFinacerelease","CompDemand","DevelopmentList",
                       "CompOtherdeclare","CompSupportFund","CompPersonNum","CompCarrierleases","Project");     
    var $helpers=array('Pagination','Html','Javascript','Form','Fck','Str','Action');
    var $components = array ('Pagination');
    var $layout='hindex';
    
    //首页内容
    function index() {
        
        $cuser=$this->Session->read('User');
        if (!$cuser){
            $this->redirect('/users/login');
        }

        $pagesize = 10;
        $paging['show'] = $pagesize;
        $paging['url'] = '/notices/index/';
        $urlcount = 0;
        
        $where = "";
        $where.= "(Notice.is_deleted = 0)";
        $urlcount = $this->Notice->findCount($where);
        $paging['total'] = $urlcount;
        $showpage = 0;
        $users = array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            
            $this->Notice->bindModel(array('hasMany'=>array('Attachment'=>array(
                'conditions'=> '',
                'fields' => 'file_name, file_path, id',
                'type' => 'RIGHT',
                'className' => 'Attachment',
                'foreignKey' => 'pid')
            )));
            
            $notices = $this->Notice->findAll($where,
            "`Notice`.`id`, `Notice`.`title`, `Notice`.`content`,`Notice`.`date`,","Notice.date desc",$limit,$page);
            if( $urlcount > $pagesize ){
                $showpage = 1;
            }
        }
        $this->set(compact('notices','showpage'));
        
    }
    
    function add(){
        $cuser=$this->Session->read('User');
        if (!$cuser){
            $this->redirect('/users/login');
        }

        if (!empty($this->data)) {
            if ($this->Notice->save($this->data)) {
                if(!empty($_POST['upload'])){
                    $uploads = $_POST['upload'];
                   // var_dump($uploads);
                    $this->Attachment->updateAll(
                        array('Attachment.pid' => "'".$this->Notice->id."'"),
                        array('Attachment.id' => $uploads)
                    );
                }

                $this->Session->setFlash('公告发布成功!');
                $this->redirect(array('action' => 'index'));
                
            }
        }
    }
    
    //编辑公告
    function edit($id = null) {
        $cuser=$this->Session->read('User');
        if (!$cuser){
            $this->redirect('/users/login');
        }

       $this->Notice->id = $id;
            if (empty($this->data)) {
                 $this->data = $this->Notice->read();
            } else {
                if ($this->Notice->save($this->data)) {
                     $this->Session->setFlash('部门信息修改成功.');
                     $this->redirect(array('action' => 'index'));
            }
        }
        if(!empty($_POST['upload'])){
            $uploads = $_POST['upload'];
           // var_dump($uploads);
            $this->Attachment->updateAll(
                array('Attachment.pid' => "'".$this->Notice->id."'"),
                array('Attachment.id' => $uploads)
            );
        }

        $where = "";
        $where .= "Attachment.pid = '".$id."'";
        $attachments = $this->Attachment->findAll($where);
        $this->set(compact('id','attachments'));
    }
    
    //删除公告
    function deletenotice($noticeid){
        $notice = $this->Notice->findById($noticeid);
        $notice["Notice"]["is_deleted"] = 1;
        $this->Notice->save($notice);
        $this->Session->setFlash('公告删除成功.');
        $this->redirect(array('action'=>'index'));
    }
    
    //查看公告
    function view($noticeid){
        $cuser=$this->Session->read('User');
        if (!$cuser){
            $this->redirect('/users/login');
        }

        $where = "";
        $where.= "(Notice.is_deleted = 0 and Notice.id = ".$noticeid.")";
        $this->Notice->bindModel(array('hasMany'=>array('Attachment'=>array(
            'conditions'=> '',
            'fields' => 'file_name, file_path',
            'type' => 'RIGHT',
            'className' => 'Attachment',
            'foreignKey' => 'pid')
        )));
        $notice = $this->Notice->find($where);
        $this->set(compact('notice'));
    }
    
   //上传附件
   function upload(){
        
        if(!empty($_FILES['upload']['name'])){
            $user_id = $this->User->id;
            App::import('Helper', 'Action');
            $actionf = new ActionHelper();
            
            //$photo=$this->data["Company"]["photo"];
            $file=$_FILES['upload'];
            
            $dirpath="upload/files/";
            if(!is_dir($dirpath)){
                mkdir($dirpath, 0777, true);
            }
            $imgpath=$actionf->upload_file($file,$dirpath);
            $attachment['file_name']=$_FILES['upload']['name'];
            $attachment['file_path']=$dirpath.$imgpath;
            
            if($this->Attachment->save($attachment)){
                
                $attachment['file_id']=$this->Attachment->id;
                echo  json_encode($attachment);
                
            }
        }
        exit;
    }
    
    //访客浏览公告列表
    function visit_index(){

           $this->layout = 'vindex';
           $this->name = 'notices';
           $this->action = 'visit_index';

        
        $pagesize = 10;
        $paging['show'] = $pagesize;
        $paging['url'] = '/notices/visit_index/';
        $urlcount = 0;
        
        $where = "";
        $where.= "(Notice.is_deleted = 0)";
        $urlcount = $this->Notice->findCount($where);
        $paging['total'] = $urlcount;
        $showpage = 0;
        $users = array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            
            $this->Notice->bindModel(array('hasMany'=>array('Attachment'=>array(
                'conditions'=> '',
                'fields' => 'file_name, file_path, id',
                'type' => 'RIGHT',
                'className' => 'Attachment',
                'foreignKey' => 'pid')
            )));
            
            $notices = $this->Notice->findAll($where,
            "`Notice`.`id`, `Notice`.`title`, `Notice`.`content`,`Notice`.`date`,","Notice.date desc",$limit,$page);
            if( $urlcount > $pagesize ){
                $showpage = 1;
            }
        }
        $this->set(compact('notices','showpage'));		

    }

    //访客浏览公告详情
    function visit_view($noticeid){

		ClassRegistry::init('Notice')->saveClick($noticeid);
    	
           $this->layout = 'vindex';
           $this->name = 'notices';
           $this->action = 'visit_view';

        $where = "";
        $where.= "(Notice.is_deleted = 0 and Notice.id = ".$noticeid.")";
        $this->Notice->bindModel(array('hasMany'=>array('Attachment'=>array(
            'conditions'=> '',
            'fields' => 'file_name, file_path',
            'type' => 'RIGHT',
            'className' => 'Attachment',
            'foreignKey' => 'pid')
        )));
        $notice = $this->Notice->find($where);
        $this->set(compact('notice'));
        
    }

    //打开页面前执行的方法
    function beforeFilter(){
        parent::beforeFilter();
    }
    
    //更新大科园，科创园信息
    // [529ebddb-a1d4-464f-85d8-0b64cbdd56cb] => 大科园 custp  [529ebde5-a954-42ee-b9f3-0b64cbdd56cb] => 科创园kustp
    function updatecompany(){
		$this->layout = 'hindex';
    }
   
    function updatedo($step){
    	header("Content-Type: text/html; charset=utf-8");
    	$custplog="";
    	$kustplog="";
    	if($step == "1"){
    		//$this->delDataSource("529ebddb-a1d4-464f-85d8-0b64cbdd56cb");					//删除原来数据
			//$this->delDataSource("529ebde5-a954-42ee-b9f3-0b64cbdd56cb");
			//echo "删除大科园，科创园数据成功";
    	}
    	if($step == "2"){
    		//echo "开始下载大科园最新数据...";
    	}
    	if($step == "3"){
			$custp = $this->preParkDateUpdata("custp","529ebddb-a1d4-464f-85d8-0b64cbdd56cb");    //更新大科园数据
			//$custplog = "更新获得大科园企业：".$custp."个      ";
			$fp=fopen("../../doc/UpdateLog.txt",'a+');
        	$cuser=$this->Session->read('User');
			$log = $cuser["username"].",".date('Y-m-d H:i:s',time())." ,".$custp.",";
        	fwrite($fp,$log);
        	fclose($fp);
    	}
    	if($step == "4"){
    		//echo "开始下载科创园最新数据...";
    	}
    	if($step == "5"){
			$kustp = $this->preParkDateUpdata("kustp","529ebde5-a954-42ee-b9f3-0b64cbdd56cb");    //更新科创园数据
			//echo "下载科创园数据成功";
			//$kustplog = "更新获得科创园企业：".$kustp."个      ";
			$fp=fopen("../../doc/UpdateLog.txt",'a+');
        	$cuser=$this->Session->read('User');
			$log = $kustp."#" ;
        	fwrite($fp,$log);
        	fclose($fp);
    	}
        if($step == "6"){
    		//echo "数据更新成功，点击<a href='http://ljrctest.sturgeon.mopaas.com/companys/index'>跳转至首页</a>";
    	}

		exit;
    }
        
    private function preParkDateUpdata($useDB,$groupid){
    	set_time_limit(0);
    	$this->changeDataSource($useDB);   //从其他数据库获取数据
		
    	//要求：从大科园，科创园中获取领军人才 姑苏人才计划的企业
        $companysid = $this->CompTalent->getCidByTypeid("'8bc65482-1085-1f5e-e3ed-b1c8f5edb645','d9b9814b-4714-1a6e-442a-1912bbb6c70b'");
		$where= "Company.id in ($companysid)";
        $companys = $this->Company->findAll($where);//符合要求的企业
        
		$len=count($companys);
		for($i=0;$i<$len;$i++){
			$trackinfo[$i] = $this->CompTrackinfo->findAll("CompTrackinfo.cid = '".$companys[$i]["Company"]["id"]."'");//企业项目追踪
			$page[$i] = $this->CompPage->findAll("CompPage.cid = '".$companys[$i]["Company"]["id"]."'");
			$economic[$i] = $this->CompEconomic->findAll("CompEconomic.cid = '".$companys[$i]["Company"]["id"]."'");//企业经济情况
			$financ[$i] = $this->CompFinanc->findAll("CompFinanc.cid = '".$companys[$i]["Company"]["id"]."'");//企业融资情况
			$patent[$i] = $this->CompanyPatent->findAll("CompanyPatent.cid = '".$companys[$i]["Company"]["id"]."'");//知识产权指标
			$developmentcostc[$i] = $this->DevelopmentCost->findAll("DevelopmentCost.cid = '".$companys[$i]["Company"]["id"]."'");//研发费用投入
			$achievement[$i] = $this->Achievement->findAll("Achievement.cid = '".$companys[$i]["Company"]["id"]."'");//产学研合情况
			$technology[$i] = $this->CompTechnology->findAll("CompTechnology.cid = '".$companys[$i]["Company"]["id"]."'");//科技项目情况
			$talent[$i] = $this->CompTalent->findAll("CompTalent.cid = '".$companys[$i]["Company"]["id"]."'");//人才项目情况
			$otherdeclare[$i] = $this->CompOtherdeclare->findAll("CompOtherdeclare.cid = '".$companys[$i]["Company"]["id"]."'");//其他项目申报情况
			$finacerelease[$i] = $this->CompFinacerelease->findAll("CompFinacerelease.cid = '".$companys[$i]["Company"]["id"]."'");//融资需求情况
			$demand[$i] = $this->CompDemand->findAll("CompDemand.cid = '".$companys[$i]["Company"]["id"]."'");//融资需求情况
			$persons[$i] = $this->CompPerson->findAll("CompPerson.cid = '".$companys[$i]["Company"]["id"]."'");//企业人才指标  
			$pro_cavalue[$i] = $this->ProCvalue->findAll("ProCvalue.pid = '".$companys[$i]["Company"]["id"]."'"); //所属产业
    		$type[$i] = $this->CompType->findAll("CompType.cid = '".$companys[$i]["Company"]["id"]."'");			//企业类型
    		$carrierleases[$i]= $this->CompCarrierleases->findAll("CompCarrierleases.cid = '".$companys[$i]["Company"]["id"]."'");
    		$informationfrom[$i] = $this->Informationfrom->findAll("Informationfrom.pid = '".$companys[$i]["Company"]["pid"]."'");
    		$project[$i] = $this->Project->findAll("Project.id = '".$companys[$i]["Company"]["pid"]."'");
		}
		
		$this->changeDataSource('default');			//回归原来数据库
		
		for($i=0;$i<$len;$i++){
			$companys[$i]["Company"]["groupid"]=$groupid;//大科园
			$companys[$i]["Company"]["is_fromupdate"]="1";
			$this->Company->save($companys[$i]);
			$this->prePartSave("CompTrackinfo",$trackinfo[$i]);
			$this->prePartSave("CompPage",$page[$i]);
			$this->prePartSave("CompEconomic",$economic[$i]);
			$this->prePartSave("CompFinanc",$financ[$i]);
			$this->prePartSave("CompanyPatent",$patent[$i]);
			$this->prePartSave("DevelopmentCost",$developmentcostc[$i]);
			$this->prePartSave("Achievement",$achievement[$i]);
			$this->prePartSave("CompTechnology",$technology[$i]);
			$this->prePartSave("CompTalent",$talent[$i]);
			$this->prePartSave("CompOtherdeclare",$otherdeclare[$i]);
			$this->prePartSave("CompFinacerelease",$finacerelease[$i]);
			$this->prePartSave("CompDemand",$demand[$i]);
			$this->prePartSave("CompPerson",$persons[$i]);
			$this->prePartSave("ProCvalue",$pro_cavalue[$i]);
			$this->prePartSave("CompType",$type[$i]);
			$this->prePartSave("CompCarrierleases",$carrierleases[$i]);
			$this->prePartSave("Informationfrom",$informationfrom[$i]);
			$this->prePartSave("Project",$project[$i]);
		}
		return $len;
    	
    }
    
    //转换数值(  未用   )
   	private function change_cvalue($val,$groupid,$idkind){
   		$idkind=="pid"? $kind="ProCvalue" : $kind="CompType";
   		if($groupid=="529ebddb-a1d4-464f-85d8-0b64cbdd56cb")//大科园
   		{
   			for($i=0;$i<count($val);$i++){
   				if($val[$i][$kind]["cvid"]==""){
   					$val[$i][$kind]["cvid"]="";
   				}else if($val[$i][$kind]["cvid"]==""){
   					$val[$i][$kind]["cvid"]="";
   				}
   			}
   		}else if($groupid=="529ebde5-a954-42ee-b9f3-0b64cbdd56cb")//科创园
   			{
   			
   			}
   		
   	}
    
    
    private function changeDataSource($dataname){
    	$this->Company->setDataSource($dataname);			
		$this->CompPerson->setDataSource($dataname);
    	$this->CompTrackinfo->setDataSource($dataname);
    	$this->CompPage->setDataSource($dataname);
		$this->CompEconomic->setDataSource($dataname);
		$this->CompFinanc->setDataSource($dataname);
		$this->CompanyPatent->setDataSource($dataname);
		$this->DevelopmentCost->setDataSource($dataname);
		$this->Achievement->setDataSource($dataname);
		$this->CompTechnology->setDataSource($dataname);
		$this->CompTalent->setDataSource($dataname);
		$this->CompOtherdeclare->setDataSource($dataname);
		$this->CompFinacerelease->setDataSource($dataname);
		$this->CompDemand->setDataSource($dataname);	 
		$this->ProCvalue->setDataSource($dataname);
		$this->CompType->setDataSource($dataname);
		$this->CompCarrierleases->setDataSource($dataname);
		$this->Project->setDataSource($dataname);
		$this->Informationfrom->setDataSource($dataname);
    }
    
    private function delDataSource($groupid){
    	$companys = $this->Company->findAll("groupid='".$groupid."' and is_fromupdate ='1'");
    	$len=count($companys);
    	for($i=0;$i<$len;$i++){
    		$this->CompTrackinfo->deleteAll("CompTrackinfo.cid = '".$companys[$i]["Company"]["id"]."'");//企业项目追踪
    		$this->CompPage->deleteAll("CompPage.cid = '".$companys[$i]["Company"]["id"]."'");
			$this->CompEconomic->deleteAll("CompEconomic.cid = '".$companys[$i]["Company"]["id"]."'");//企业经济情况
			$this->CompFinanc->deleteAll("CompFinanc.cid = '".$companys[$i]["Company"]["id"]."'");//企业融资情况
			$this->CompanyPatent->deleteAll("CompanyPatent.cid = '".$companys[$i]["Company"]["id"]."'");//知识产权指标
			$this->DevelopmentCost->deleteAll("DevelopmentCost.cid = '".$companys[$i]["Company"]["id"]."'");//研发费用投入
			$this->Achievement->deleteAll("Achievement.cid = '".$companys[$i]["Company"]["id"]."'");//产学研合情况
			$this->CompTechnology->deleteAll("CompTechnology.cid = '".$companys[$i]["Company"]["id"]."'");//科技项目情况
			$this->CompTalent->deleteAll("CompTalent.cid = '".$companys[$i]["Company"]["id"]."'");//人才项目情况
			$this->CompOtherdeclare->deleteAll("CompOtherdeclare.cid = '".$companys[$i]["Company"]["id"]."'");//其他项目申报情况
			$this->CompFinacerelease->deleteAll("CompFinacerelease.cid = '".$companys[$i]["Company"]["id"]."'");//融资需求情况
			$this->CompDemand->deleteAll("CompDemand.cid = '".$companys[$i]["Company"]["id"]."'");//融资需求情况	
    		$this->CompPerson->deleteAll("CompPerson.cid = '".$companys[$i]["Company"]["id"]."'");
    		$this->ProCvalue->deleteAll("ProCvalue.pid = '".$companys[$i]["Company"]["id"]."'");
    		$this->CompType->deleteAll("CompType.cid = '".$companys[$i]["Company"]["id"]."'");
    		$this->CompCarrierleases->deleteAll("CompCarrierleases.cid = '".$companys[$i]["Company"]["id"]."'");
    		$this->Informationfrom->deleteAll("Informationfrom.pid = '".$companys[$i]["Company"]["pid"]."'");
    		$this->Project->deleteAll("Project.id = '".$companys[$i]["Company"]["pid"]."'");
    	}
		$this->Company->deleteAll("groupid='".$groupid."' and is_fromupdate ='1'");
    }
    
	private function prePartSave($partname,$data){ //每个子目录中数据的添加
		for($j=0;$j<count($data);$j++){
				$this->$partname->save($data[$j]);
			}
	}    
    
    
    
    
    
}
?>